package com.xzc.lease.web.app.custom.converter;

import com.xzc.lease.common.exception.LeaseException;
import com.xzc.lease.common.result.ResultCodeEnum;
import com.xzc.lease.model.enums.BaseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author 徐生
 * 2024/10/15
 * description：string类型自动转换枚举类型
 */
@Component
@Slf4j
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String code) {
                log.info("接受前端请求，code转换枚举类，code={}", code);
                //targetType：即是我们指定泛型的BaseEnum
                //code：即指定的泛型String
                //getEnumConstants：获得所有BaseEnum的实现类的实例
                T[] enumConstants = targetType.getEnumConstants();
                for (T enumConstant : enumConstants) {
                    //当前实例的code = 前端传来的code，则返回当前实例
                    if (enumConstant.getCode().equals(Integer.valueOf(code))) {
                        return enumConstant;
                    }
                }
                //循环结束说明转换失败，抛出异常
                throw new LeaseException(ResultCodeEnum.ENUM_CONVERTER_ERROR);
            }
        };
    }
}
